package com.ehais.analysis;



import android.util.Log;


import com.ehais.model.NewScanBatteryData;
import com.ehais.model.NewScanBatteryModel;
import com.ehais.model.StationInfo;
import com.ehais.model.StationResult;
import com.ehais.util.AsciiToHex;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Phosphoric {

    private static final String TAG="WifiUtil";

    //    public static List<JSONObject> list = new ArrayList<JSONObject>();
    private static JSONArray scanArray = new JSONArray();

    public static volatile Phosphoric instance;

    private static int frequencyTimerSubmit = 60000;//每隔60秒上传一次数据
    private static long tmpTimerSubmit = 0;//临时赋值

    public static Phosphoric getInstance() {
        if (instance == null) {
            synchronized (Phosphoric.class) {
                instance = new Phosphoric();
                while (scanArray.length() > 0) scanArray.remove(0);
            }
        }
        return instance;
    }

    //清空缓存数据
    public static void clear(){
        while (scanArray.length() > 0) scanArray.remove(0);
    }

    public static void add(StationInfo stationResult){
        try{
            JSONObject scanJSON = new JSONObject();
            scanJSON.put("stationId", stationResult.getId());
            scanJSON.put("battery", new JSONObject());
            scanJSON.put("data", new JSONArray());
            scanArray.put(scanJSON);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public static void initGather(){ //开始正式采集进行初始化
        tmpTimerSubmit = System.currentTimeMillis();
    }


    public static void submit(){
        try{
            if((System.currentTimeMillis() - tmpTimerSubmit) > frequencyTimerSubmit){
                tmpTimerSubmit = System.currentTimeMillis();
//                ApiService apiService= ApiRetrofit.getApiRetrofit().getApiService();
//                Log.i("Phosphoric","磷锂上传数据："+scanArray.toString());
//                Observable<Result> observable = apiService.uploadBatteryTL(java.net.URLEncoder.encode(scanArray.toString(),"UTF-8"));
//                Subscriber subscriber=new Subscriber<String>() {
//                    @Override
//                    public void onCompleted() {
//                        Log.i("Phosphoric","磷锂上传数据成功了!!!!");
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        e.printStackTrace();
//                        Log.i("Phosphoric","磷锂上传数据失败了!!!!");
//                    }
//
//                    @Override
//                    public void onNext(String o) {
//                        Log.i("Phosphoric","onNext:"+o);
//                    }
//                };
//                observable.subscribe(subscriber);

                for(int i = 0 ; i < scanArray.length() ; i ++){
                    JSONObject json = scanArray.getJSONObject(i);
                    json.put("data",new JSONArray());
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }





    public static NewScanBatteryData measurement(String data, Integer sequenceIndex){
        NewScanBatteryData newScanBatteryData = new NewScanBatteryData();
        newScanBatteryData.setAlarmVoltage(0);//初始化不告警
        newScanBatteryData.setAlarmElectricity(0);//初始化
        String msg = "";// data+"\r\n";

//        JSONObject explain = new JSONObject();

        String address = data.substring(3,5);
        newScanBatteryData.setAddress(address);

        int p = 1;

        p += 16 ;
//        p += 12 ;
        String hex = "0x"+data.substring(p, p+2);

        Integer x = Integer.parseInt(hex.substring(2),16);
        p += 2;
//        msg += "telemetering\r\n";

        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String acquisitionTime = df.format(date);


        try{

            JSONObject json = new JSONObject();

            json.put("acquisitionTime",acquisitionTime);

            ///////////////////////////////////////////////////////////////////////////////////////////
            msg += "电压:";

            String dy = data.substring(p , p + x * 4);

            Double voltage = 0d;
            JSONArray _voltage = new JSONArray();
            List<NewScanBatteryModel> newScanBatteryList = new ArrayList<NewScanBatteryModel>();
            List<NewScanBatteryModel> newScanBatteryList0 = new ArrayList<NewScanBatteryModel>();
            List<NewScanBatteryModel> newScanBatteryList1 = new ArrayList<NewScanBatteryModel>();

            List<Double> monomerVoltageList = new ArrayList<Double>();

            for(int i = 0 ; i < x ; i ++) {
                String m = "0x" + dy.substring(i * 4 ,i * 4 + 4);
                Double xm = Double.valueOf(Integer.parseInt(m.substring(2),16)) / 1000;
                _voltage.put(xm.toString());
                voltage += xm;
//                msg += "电压"+(i+1)+"为:"+xm +"V\r\n";
                msg += xm +"V  ";
                p += 4;
//                Integer alarm = 0;
//                if(xm <= 2.5){
//                    newScanBatteryData.setAlarmVoltage(1);//初始化不告警
//                    alarm = 1;
//                }
//
//                newScanBatteryList.add(new NewScanBatteryModel("BAT-"+(i+1)+":",String.format("%.3f",xm )+"V",alarm));
//                newScanBatteryList0.add(new NewScanBatteryModel("BAT-"+(i+1)+":",String.format("%.3f",xm )+"V",alarm));

                monomerVoltageList.add(Double.valueOf(String.format("%.3f",xm )));
            }

//            json.put("totalVoltage",String.format("%.2f",voltage));
//            newScanBatteryData.setVoltage(String.format("%.2f",voltage)+"V");

            newScanBatteryData.setMonomerVoltageList(monomerVoltageList);

//            newScanBatteryData.setAlarmVoltage(0);//初始化不告警
//            if(voltage <= 48.5){
//                newScanBatteryData.setAlarmVoltage(1);//初始化不告警
//            }

            msg += "\r\n";
            json.put("monomerVoltageList",_voltage);
            json.put("voltage",voltage.toString());
//            explain.put("monomerVoltageList","电压数据");
//            explain.put("voltage","总电压");

            String dx = "0x"+data.substring( p , p + 2);
            p += 2;

            Integer dxx = Integer.parseInt(dx.substring(2),16);

            String dxy = data.substring( p , p + dxx * 4);

            msg += "温度：";

            JSONArray temperature = new JSONArray();
            List<Double> temperatureList = new ArrayList<Double>();
            for(int i = 0 ; i < dxx ; i ++) {
//                String m =  dxy.substring(i * 4 ,i * 4 + 4);
                String m = "0x" + dy.substring(i * 4 ,i * 4 + 4);
//                Integer xm = Integer.parseInt(("0x" + m).substring(2),16);
                Double xm = Double.valueOf(Integer.parseInt(m.substring(2),16) ) / 100;
                temperature.put(xm.toString());
//                msg += "温度"+(i+1)+"为:"+xm+"C \r\n";
                msg += xm+"℃  ";
                p += 4;

//                Integer alarm = 0;
//                if(xm >= 50){
//                    newScanBatteryData.setAlarmVoltage(1);//初始化不告警
//                    alarm = 1;
//                }
//
//                newScanBatteryList.add(new NewScanBatteryModel("温度-"+(i+1)+":",String.format("%.2f",xm)+"℃",alarm));
//                newScanBatteryList1.add(new NewScanBatteryModel("温度-"+(i+1)+":",String.format("%.2f",xm)+"℃",alarm));
                temperatureList.add(Double.valueOf(String.format("%.2f",xm)));

            }
//            json.put("temperature",temperature);
            newScanBatteryData.setTemperatureList(temperatureList);
//            explain.put("temperature","温度数据");
//            newScanBatteryData.setNewScanBatteryModelList(newScanBatteryList);
//            newScanBatteryData.setNewScanBatteryModelList0(newScanBatteryList0);
//            newScanBatteryData.setNewScanBatteryModelList1(newScanBatteryList1);


            //环境温度
            String environmentTemperature = data.substring( p , p + 4);
            Integer _environmentTemperature = Integer.parseInt(("0x" + environmentTemperature).substring(2),16);
            p += 4;
            msg += "环境温度为:"+_environmentTemperature+"\r\n";
            json.put("environmentTemperature",_environmentTemperature.toString());
//            explain.put("environmentTemperature","环境温度");


            //MOS温度
            String mosTemperature = data.substring( p , p + 4);
            Integer _mosTemperature = Integer.parseInt(("0x" + mosTemperature).substring(2),16);
            p += 4;
            msg += "MOS温度为:"+_mosTemperature+"\r\n";
            json.put("mosTemperature",_mosTemperature.toString());
//            explain.put("mosTemperature","MOS温度");

            //电池电流数据
            String electricity = data.substring( p , p + 4);
            Double _electricity = Double.valueOf(Integer.parseInt(("0x" + electricity).substring(2),16)) / 10000;// 原来是：100000
            p += 4;
            msg += "电池电流数据为:"+_electricity+"\r\n";
//            json.put("electricity",_electricity.toString());
            json.put("current",_electricity.toString());
//            newScanBatteryData.setElectricity(String.format("%.3f",_electricity) + "A");
//            explain.put("electricity","电池电流");


//            if(_electricity >= 200 || _electricity <= 0){
//                newScanBatteryData.setAlarmElectricity(1);//电流异常告警
//            }

            //电池总压数据
            String totalVoltage = data.substring( p , p + 4);
            Double _totalVoltage = Double.valueOf(Integer.parseInt(("0x" + totalVoltage).substring(2),16)) / 100;
            p += 4;
            msg += "电池总压数据为:"+_totalVoltage+"\r\n";
//            json.put("totalVoltage",String.format("%.2f",_totalVoltage));


//            explain.put("totalVoltage","电池总电压");

            //电池剩余容量
            String residueElectric = data.substring( p , p + 4);
            Integer _residueElectric = Integer.parseInt(("0x" + residueElectric).substring(2),16);

            p += 4;
            msg += "电池剩余容量为:"+_residueElectric+"\r\n";
            json.put("residueElectric",_residueElectric.toString());


//            explain.put("residueElectric","电池剩余容量");

            //电池总容量
            String totalElectric = data.substring( p , p + 4);
            Integer _totalElectric = Integer.parseInt(("0x" + totalElectric).substring(2),16);
            p += 4;
            msg += "电池总容量为:"+_totalElectric+"\r\n";
            json.put("totalElectric",_totalElectric.toString());
            json.put("soc",_totalElectric.toString());
//            explain.put("totalElectric","电池总容量");


            //电池循环次数
//            String circulation = data.substring( p , p + 4);
//            Integer _circulation = Integer.parseInt(("0x" + circulation).substring(2),16);
//            p += 4;
//            msg += "电池循环次数为:"+_circulation+"\r\n";
//            json.put("circulation",_circulation.toString());
//            explain.put("circulation","电池循环次数");
            JSONObject sequenceJSONObject = (JSONObject)scanArray.get(sequenceIndex);
            JSONArray sequenceJSONArrayData = sequenceJSONObject.getJSONArray("data");
            sequenceJSONArrayData.put(json);
        }catch (Exception e){
            e.printStackTrace();
        }

        return newScanBatteryData;
    }


    public static NewScanBatteryData signal(String data,Integer sequenceIndex){
        NewScanBatteryData newScanBatteryData = new NewScanBatteryData();
//        newScanBatteryData.setAlarmVoltage(0);
//        newScanBatteryData.setAlarmElectricity(0);
//        newScanBatteryData.setAlarmElectricity0(0);
//        newScanBatteryData.setAlarmVoltage0(0);
//        newScanBatteryData.setAlarmElectricity1(0);
//        newScanBatteryData.setAlarmVoltage1(0);
        String msg = "";//data+"\r\n";

//        JSONObject explain = new JSONObject();

        int p = 1;

//        p += 16 ;
        p += 12 ;
        String hex = "0x"+data.substring(p, p+2);

        Integer x = Integer.parseInt(hex.substring(2),16);
        p += 2;
//        msg += "teleindication\r\n";


        try{
            JSONObject sequenceJSONObject = (JSONObject)scanArray.get(sequenceIndex);
            JSONArray sequenceJSONArrayData = sequenceJSONObject.getJSONArray("data");
            JSONObject json = sequenceJSONArrayData.getJSONObject(sequenceJSONArrayData.length() - 1);

//            JSONObject obj = list.get(list.size() - 1);
//            JSONArray dataArray = obj.getJSONArray("data");
//            JSONObject json = dataArray.getJSONObject (dataArray.length() - 1);

            ///////////////////////////////////////////////////////////////////////////////////////////


            String dy = data.substring(p , p + x * 2);
//            System.out.println("dy:"+dy);

            msg += "电压告警状态值 ：";

            JSONArray alarmVoltageList = new JSONArray();
            for(int i = 0 ; i < x ; i ++) {
                String m = "0x" + dy.substring(i * 2 ,i * 2 + 2);
                Integer xm = Integer.parseInt(m.substring(2),16);
                alarmVoltageList.put(xm.toString());
//                System.out.println((i+1)+"电压告警状态值 ： "+m +"  ==>  "+ xm);
                p += 2;
//                msg += "电压告警状态值 ："+m+"\r\n";
                msg += ""+m+" ";
            }

            msg += "\r\n";

            json.put("alarmVoltageList", alarmVoltageList);
//            explain.put("alarmVoltageList","电压告警状态值");

            String dx = "0x"+data.substring( p , p + 2);
            p += 2;

//            System.out.println("温度数量：dx=>"+dx);

            Integer dxx = Integer.parseInt(dx.substring(2),16);
//            System.out.println("温度数量：dx=>dxx=>"+dxx);

            String dxy = data.substring( p , p + dxx * 2);
            System.out.println(dxy);

            msg += "温度：";

            JSONArray alarmTemperature = new JSONArray();
            for(int i = 0 ; i < dxx ; i ++) {
                String m =  dxy.substring(i * 2 ,i * 2 + 2);
                Integer xm = Integer.parseInt(("0x" + m).substring(2),16);
//                System.out.println((i+1)+"温度告警状态值 ： "+m +"  ==>  "+ xm);
                alarmTemperature.put(xm.toString());
                p += 2;
//                msg += "温度告警状态值 ："+m+"\r\n";
                msg += ""+m+" ";
            }
            msg += "\r\n";
            json.put("alarmTemperature", alarmTemperature);
//            explain.put("alarmTemperature","温度告警状态值");

            //环境温度告警状态
            String alarmEnvironmentTemperature = data.substring( p , p + 2);
            Integer _alarmEnvironmentTemperature = Integer.parseInt(("0x" + alarmEnvironmentTemperature).substring(2),16);System.out.println(_alarmEnvironmentTemperature+"//环境温度告警");
//            explain.put("alarmEnvironmentTemperature", "环境温度告警状态");
            json.put("alarmEnvironmentTemperature", _alarmEnvironmentTemperature.toString());
            msg += "环境温度告警状态 ："+_alarmEnvironmentTemperature+"\r\n";


            p += 2;
            //MOS 温度告警状态
            String alarmMosTemperature = data.substring( p , p + 2);
            Integer _alarmMosTemperature = Integer.parseInt(("0x" + alarmMosTemperature).substring(2),16);System.out.println(_alarmMosTemperature+"//MOS 温度告警状态");
            p += 2;
//            explain.put("alarmMosTemperature", "MOS 温度告警状态");
            json.put("alarmMosTemperature", _alarmMosTemperature.toString());
            msg += "MOS 温度告警状态 ："+_alarmMosTemperature+"\r\n";

            //充放电流告警状态
            String alarmEelectricity = data.substring( p , p + 2);
            Integer _alarmElectricity = Integer.parseInt(("0x" + alarmEelectricity).substring(2),16);System.out.println(_alarmElectricity+"//充放电流告警状态");
            p += 2;
//            explain.put("alarmEelectricity", "充放电流告警状态");
            json.put("alarmEelectricity", _alarmElectricity.toString());
            msg += "充放电流告警状态 ："+_alarmElectricity+"\r\n";
            newScanBatteryData.setAlarmElectricity(_alarmElectricity);

            //电池总压告警状态
            String alarmTotalVoltage = data.substring( p , p + 2);
            Integer _alarmTotalVoltage = Integer.parseInt(("0x" + alarmTotalVoltage).substring(2),16);System.out.println(_alarmTotalVoltage+"//电池总压告警状态");
            p += 2;
//            explain.put("alarmTotalVoltage", "电池总压告警状态");
            json.put("alarmTotalVoltage", _alarmTotalVoltage.toString());
            msg += "电池总压告警状态 ："+_alarmTotalVoltage+"\r\n";
            newScanBatteryData.setAlarmVoltage(_alarmTotalVoltage);


            //自定义告警量数量
            String residueElectric = data.substring( p , p + 2);
            Integer _residueElectric = Integer.parseInt(("0x" + residueElectric).substring(2),16);System.out.println(residueElectric+"//自定义告警量数量");
            p += 2;
//            explain.put("residueElectric", "自定义告警量数量");
            json.put("residueElectric", _residueElectric.toString());
            msg += "自定义告警量数量 ："+_residueElectric+"\r\n";


            //均衡事件代码
            String totalElectric = data.substring( p , p + 2);
            Integer _totalElectric = Integer.parseInt(("0x" + totalElectric).substring(2),16);System.out.println(totalElectric+"//均衡事件代码");
            p += 2;
//            explain.put("totalElectric", "均衡事件代码");
            json.put("totalElectric", _totalElectric.toString());
            msg += "均衡事件代码 ："+_totalElectric+"\r\n";


            //电压事件代码
            String circulation = data.substring( p , p + 2);
            Integer _circulation = Integer.parseInt(("0x" + circulation).substring(2),16);System.out.println(circulation+"//电压事件代码");
            p += 2;
//            explain.put("circulation", "电压事件代码");
            json.put("circulation", _circulation.toString());
            msg += "电压事件代码 ："+_circulation+"\r\n";

            //温度事件代码
            String eventTemperature = data.substring( p , p + 4);
            Integer _eventTemperature = Integer.parseInt(("0x" + eventTemperature).substring(2),16);System.out.println(circulation+"//温度事件代码");
            p += 4;
//            explain.put("eventTemperature", "温度事件代码");
            json.put("eventTemperature", _eventTemperature.toString());
            msg += "温度事件代码 ："+_eventTemperature+"\r\n";


            //电流事件代码
            String eventElectric = data.substring( p , p + 2);
            Integer _eventElectric = Integer.parseInt(("0x" + eventElectric).substring(2),16);System.out.println(_eventElectric+"//电流事件代码");
            p += 2;
//            explain.put("eventElectric", "电流事件代码");
            json.put("eventElectric", _eventElectric.toString());
            msg += "电流事件代码 ："+_eventElectric+"\r\n";


            //剩余容量告警
            String residueCapacity = data.substring( p , p + 2);
            Integer _residueCapacity = Integer.parseInt(("0x" + residueCapacity).substring(2),16);System.out.println(_residueCapacity+"//剩余容量告警");
            p += 2;
//            explain.put("residueCapacity", "剩余容量告警");
            json.put("residueCapacity", _residueCapacity.toString());
            msg += "剩余容量告警 ："+_residueCapacity+"\r\n";


            //FET 状态代码
//            String fetCode = data.substring( p , p + 2);
//            Integer _fetCode = Integer.parseInt(("0x" + fetCode).substring(2),16);System.out.println(_eventElectric+"//FET 状态代码");
//            p += 2;
////            explain.put("fetCode", "FET 状态代码");
//            json.put("fetCode", _fetCode.toString());
//            msg += "FET 状态代码 ："+_fetCode+"\r\n";


            //系统状态代码
//            String systemCode = data.substring( p , p + 2);
//            Integer _systemCode = Integer.parseInt(("0x" + systemCode).substring(2),16);System.out.println(_eventElectric+"//系统状态代码");
//            p += 2;
////            explain.put("systemCode", "系统状态代码");
//            json.put("systemCode", _systemCode.toString());
//            msg += "系统状态代码 ："+_systemCode+"\r\n";


            //均衡状态代码
//            String equilibriumStatusCode = data.substring( p , p + 2);
//            Integer _equilibriumStatusCode = Integer.parseInt(("0x" + equilibriumStatusCode).substring(2),16);System.out.println(_eventElectric+"//均衡状态代码");
//            p += 2;
////            explain.put("equilibriumStatusCode", "均衡状态代码");
//            json.put("equilibriumStatusCode", _equilibriumStatusCode.toString());
//            msg += "均衡状态代码 ："+_equilibriumStatusCode+"\r\n";

            //预留今后扩展
//            String dex = data.substring( p , p + 4);System.out.println(dex+"//预留今后扩展");

//            json.put("explain",explain);
//            System.out.println(json.toString());



//            return json;
        }catch (Exception e){
            e.printStackTrace();
        }

        return newScanBatteryData;
    }


    public static void manufacturers(String data,Integer sequenceIndex,String address,StationInfo stationResult){

        String msg = "";// data+"\r\n";
//        JSONObject json = new JSONObject();
//        JSONObject explain = new JSONObject();

        try{
            JSONObject json = (JSONObject)scanArray.getJSONObject(sequenceIndex).getJSONObject("battery");
//            JSONObject json = list.get(list.size() - 1).getJSONObject("battery");
            json.put("batteryName","第"+address+"组蓄电池组");
            json.put("monomerNumber","16");
            json.put("capacity","100");//todo //电池额定容量
            json.put("manufacturerDate","2021-07-01");//电池入网日期
            json.put("address",address);//电池地址码

            int p = 1;
            String first = data.substring(p,p+8);
            System.out.println(first);

            p += 8 ;
            String lengthHex = "0x"+data.substring(p, p+4);
            System.out.println("lengthHex==>"+lengthHex);
            Integer lenghtX = Integer.parseInt(lengthHex.substring(2),16);
            System.out.println("hex=>lenghtX=>"+lenghtX);
            p += 4;
            String manufacturersHex = data.substring(p, p+40);
            System.out.println("manufacturersHex==>"+manufacturersHex);
            System.out.println("hex=>manufacturersX=>"+ AsciiToHex.hexToAscii(manufacturersHex));
            json.put("manufacturerPinYin",AsciiToHex.hexToAscii(manufacturersHex));
            json.put("identificationCode",stationResult.getId() + AsciiToHex.hexToAscii(manufacturersHex) + address);//新增唯一标识的字段
            msg += "生产厂家："+AsciiToHex.hexToAscii(manufacturersHex);
            p += 40;
            String modelNoHex = data.substring(p, p+4);
            System.out.println("modelNoHex==>"+modelNoHex);
            System.out.println("hex=>modelNoHex=>"+AsciiToHex.hexToAscii(modelNoHex));
            json.put("model",AsciiToHex.hexToAscii(modelNoHex));
            msg += "型号："+AsciiToHex.hexToAscii(modelNoHex);
            p += 4;
//            String bmsManufacturerHex = data.substring(p, p+40);
//            System.out.println("manufacturerHex==>"+bmsManufacturerHex);
//            System.out.println("hex=>bmsManufacturerHex=>"+AsciiToHex.hexToAscii(bmsManufacturerHex));
//
//            p += 40;
//            String bmsModelNoHex = data.substring(p, p+4);
//            System.out.println("bmsModelNoHex==>"+bmsModelNoHex);
//            System.out.println("hex=>BMS 型号=>"+AsciiToHex.hexToAscii(bmsModelNoHex));
//
//
//            p += 4;
//            String bmsVersionHex = data.substring(p, p+4);
//            System.out.println("bmsVersionHex==>"+bmsVersionHex);
//            System.out.println("hex=>BMS 通信软件版本号=>"+AsciiToHex.hexToAscii(bmsVersionHex));

        }catch (Exception e){
            e.printStackTrace();
        }

    }



}